import os
import sys
import subprocess
import shutil


def fix_qt_plugin_issue():
    print("=" * 50)
    print("正在修复 Qt 平台插件问题...")
    print("=" * 50)

    # 1. 获取 Python 安装路径
    python_path = os.path.dirname(sys.executable)
    print(f"Python 路径: {python_path}")

    # 2. 查找 Qt 插件路径
    qt_plugin_path = ""
    possible_paths = [
        os.path.join(python_path, "Lib", "site-packages", "PyQt5", "Qt5", "plugins"),
        os.path.join(python_path, "Lib", "site-packages", "PySide2", "plugins"),
        os.path.join(python_path, "Lib", "site-packages", "PySide6", "plugins")
    ]

    for path in possible_paths:
        if os.path.exists(path):
            qt_plugin_path = path
            print(f"找到 Qt 插件路径: {qt_plugin_path}")
            break

    if not qt_plugin_path:
        print("❌ 错误: 未找到 Qt 插件路径，请确保已安装 PyQt5/PySide")
        input("按 Enter 退出...")
        return

    # 3. 设置环境变量
    os.environ["QT_QPA_PLATFORM_PLUGIN_PATH"] = qt_plugin_path
    print(f"已设置环境变量: QT_QPA_PLATFORM_PLUGIN_PATH={qt_plugin_path}")

    # 4. 复制 DLL 文件（特殊修复）
    platforms_path = os.path.join(qt_plugin_path, "platforms")
    if os.path.exists(platforms_path):
        print("已找到 platforms 目录")

        # 复制 qwindows.dll 到脚本目录（临时修复）
        qwindows_dll = os.path.join(platforms_path, "qwindows.dll")
        if os.path.exists(qwindows_dll):
            script_dir = os.path.dirname(os.path.abspath(__file__))
            target_path = os.path.join(script_dir, "platforms")

            if not os.path.exists(target_path):
                os.makedirs(target_path)

            shutil.copy2(qwindows_dll, os.path.join(target_path, "qwindows.dll"))
            print(f"已复制 qwindows.dll 到: {target_path}")

    # 5. 检查关键文件
    print("\n检查关键文件是否存在:")
    critical_files = [
        os.path.join(platforms_path, "qwindows.dll"),
        os.path.join(qt_plugin_path, "platforms", "qminimal.dll"),
        os.path.join(qt_plugin_path, "platforms", "qoffscreen.dll")
    ]

    all_exist = True
    for file in critical_files:
        exists = os.path.exists(file)
        print(f"{'✅' if exists else '❌'} {file}")
        if not exists:
            all_exist = False

    if all_exist:
        print("\n✅ 所有关键文件存在，问题应已解决")
    else:
        print("\n❌ 缺少关键文件，请重新安装 PyQt5/PySide")

    print("\n修复完成！请重新运行主程序")
    input("按 Enter 退出...")


if __name__ == "__main__":
    fix_qt_plugin_issue()